/**
 * 
 */
package hu.raholec.controller;

import hu.raholec.controller.model.AddNodeRequest;
import hu.raholec.controller.model.AddNodeResult;
import hu.raholec.data.Content;
import hu.raholec.service.ContentService;
import hu.raholec.service.ServiceException;

import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Attila_Kevei
 * 
 */
@Controller
public class FormController {

    @Autowired
    private ContentService service;

	
	@RequestMapping(value = "form", method = RequestMethod.GET)
	public String home(@RequestParam(defaultValue="users") String path, Locale locale, Model model) {
		Content root = service.getContent(path);
		model.addAttribute("root", root.toString());
		model.addAttribute("rootName", path);
		model.addAttribute("nodes", root.getNodeNames());
		model.addAttribute("properties", root.getProperties());
		model.addAttribute("breadcrumb", service.getBreadCrumb(path));
		return "rumcajsz";
	}

	@RequestMapping(value = "/service/addNode.json", method = RequestMethod.POST)
	public @ResponseBody AddNodeResult addNode(@RequestBody AddNodeRequest request) {
		System.out.println("The form submitted as JSON: path="
				+ request.getPath() + " node=" + request.getName());

		AddNodeResult response = new AddNodeResult();
		response.setStatus(AddNodeResult.Status.ERROR);

		try {

			Assert.notNull(request);
			Assert.notNull(request.getPath());
			Assert.notNull(request.getName());
			try {
				service.addNode(request.getPath(), request.getName());
			} catch (ServiceException e) {
				System.out.println("Node creation error!");
			}
			response.setStatus(AddNodeResult.Status.OK);
			response.setId(request.getPath() + "/" + request.getName());

		} catch (Exception e) {
			// logger.error("Unable to perform addition operation ...", e);
		}

		System.out.println(response.getStatus() + " - " + response.getId());
		return response;
	}
	

}
